package com.demo.mykotlin.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.demo.mykotlin.bean.Fruit
import com.demo.mykotlin.R

/**
 * 水果回收适配器
 * @author wen66to88@163.com
 * @date 2020/5/22 - 9:29
 */
class FruitRecycleAdapter(private val FruitList: List<Fruit>) :
    RecyclerView.Adapter<FruitRecycleAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val fruitImage: ImageView = view.findViewById(R.id.fruitImage)
        val fruitName: TextView = view.findViewById(R.id.fruitName)
    }

    /**
     * 创建条目视图
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_fruit, parent, false)
        val viewHolder = ViewHolder(view)
        //设置条目监听
        viewHolder.itemView.setOnClickListener {
            val position = viewHolder.adapterPosition
            val fruit = FruitList[position]
            Toast.makeText(parent.context, "你点击的视图 ${fruit.name}", Toast.LENGTH_LONG).show()
        }
        //设置图片监听
        viewHolder.fruitImage.setOnClickListener {
            val position = viewHolder.adapterPosition
            val fruit = FruitList[position]
            Toast.makeText(parent.context, "你点击的图片 ${fruit.name}", Toast.LENGTH_LONG).show()
        }
        return viewHolder
    }

    override fun getItemCount() = FruitList.size

    /**
     * 设置条目数据
     */
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruit = FruitList[position]
        holder.fruitImage.setImageResource(fruit.imageId)
        holder.fruitName.text = fruit.name
    }

}